<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="nav-button" @click="goBack">
				<uni-icons type="left" size="24" color="#333"></uni-icons>
			</view>
			<text class="nav-title">商品详情</text>
			<view class="cart-icon" @click="gotoCart">
				<uni-icons type="cart" size="24" color="#333"></uni-icons>
			</view>
		</view>

		<!-- 商品轮播图 -->
		<swiper class="swiper" autoplay circular indicator-dots>
			<swiper-item v-for="(item, index) in swiperList" :key="index">
				<image class="swiper-img" :src="item" mode="aspectFill"></image>
			</swiper-item>
		</swiper>

		<!-- 商品信息 -->
		<view class="product-detail">
			<view class="product-name">{{ goodDetail.goodsName }}</view>
			<view class="product-description">
				{{ goodDetail.goodsDescription }}
			</view>
			<view class="price-stock">
				<view class="price">￥{{ goodDetail.goodsPrice }}</view>
				<view class="stock">库存：{{ goodDetail.stockQuantity }}件</view>
			</view>
		</view>

		<!-- 评价部分 -->
		<view class="review-section">
			<view class="review-header">
				<view class="rating">
					<text class="rating-text">4.5</text>
					<uni-icons type="star-filled" size="24" color="#ffee59"></uni-icons>
					<uni-icons type="star-filled" size="24" color="#ffee59"></uni-icons>
					<uni-icons type="star-filled" size="24" color="#ffee59"></uni-icons>
					<uni-icons type="star-filled" size="24" color="#ffee59"></uni-icons>
					<uni-icons type="starhalf" size="24" color="#ffee59"></uni-icons>
				</view>
				<view class="review-count">共128条评价</view>
			</view>
			<!-- 用户评价列表 -->
			<view class="review-list">
				<view class="review-item" v-for="(review, index) in reviewList" :key="index">
					<view class="user-info">
						<image class="user-avatar" :src="review.avatar"></image>
						<text class="user-nickname">{{ review.nickname }}</text>
					</view>
					<view class="review-content">
						<text class="review-text">{{ review.content }}</text>
						<view class="review-images">
							<image class="review-img" v-for="(img, i) in review.images" :key="i" :src="img"></image>
						</view>
					</view>
					<view class="review-time">{{ review.time }}</view>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="footer">
			<view class="footer-item" @click="handleShare">
				<uni-icons type="redo" size="25" color="#666"></uni-icons>
				<text class="footer-text">分享</text>
			</view>
			<view class="footer-item" @click="handleCollect">
				<uni-icons :type="isCollected ? 'star-filled' : 'star'" size="25"
					:color="isCollected ? '#ffd700' : '#666'"></uni-icons>
				<text class="footer-text">收藏</text>
			</view>
			<view class="footer-item cart" @click="handleCartAction" :class="{ 'cart-loading': cartLoading }">
				<uni-icons :type="isInCart ? 'cart-filled' : 'cart'" size="25" :color="isInCart ? '#ffd700' : '#666'">
				</uni-icons>
				<text class="footer-text">{{ isInCart ? '移出购物车' : '加入购物车' }}</text>
			</view>
			<view class="footer-item buy" @click="handleBuyNow">
				<text class="footer-text">立即购买</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				goodDetail: {
					goodsId: null,
					goodsName: '加载中...',
					goodsDescription: '',
					goodsPrice: 0,
					stockQuantity: 0,
					goodsImage1: '',
					goodsImage2: '',
					goodsImage3: ''
				},
				swiperList: [],
				// 用户评价数据
				reviewList: [{
						avatar: '../../static/dis-img7.jpg',
						nickname: '帆先生',
						content: '食材非常新鲜，包装也很用心，推荐购买！',
						images: [
							'../../static/comment2.png',
							'../../static/comment3.png'
						],
						time: '2025-04-10 07:49:25'
					},
					{
						avatar: '../../static/dis-img5.jpg',
						nickname: '吃货小新',
						content: '口感好，很爱吃，下次还会再来！',
						images: [
							'../../static/comment1.png'
						],
						time: '2025-04-09 14:20:10'
					},
					{
						avatar: '../../static/dis-img4.jpg',
						nickname: '小馋猫',
						content: '食材新鲜质量好，满意满意！',
						images: [
							'../../static/comment4.jpg'
						],
						time: '2025-04-07 09:15:30'
					}
				],
				userId: null,
				isInCart: false,
				isCollected: false,
				cartLoading: false,
				cartItem: null
			};
		},
		onLoad(options) {
			this.initPage(options.goodsId);
		},
		methods: {
			async initPage(goodsId) {
				await this.fetchGoodDetail(goodsId);
				await this.checkLoginStatus();
				if (this.userId) await this.checkCartStatus();
			},

			async checkLoginStatus() {
				this.userId = await this.getUserProfile();
			},

			async fetchGoodDetail(goodsId) {
				try {
					const res = await uni.request({
						url: `http://localhost:8080/goods/goods/${goodsId}`,
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});
					if (res.data.code === 200) {
						this.goodDetail = res.data.data;
						this.initSwiperImages();
					}
				} catch (error) {
					uni.showToast({
						title: '加载商品失败',
						icon: 'none'
					});
				}
			},
			// 跳转到购物车页面
			gotoCart() {
				uni.switchTab({
					url: '/pages/shop-cart/shop-cart'
				});
			},
			initSwiperImages() {
				this.swiperList = [
					this.formatImageUrl(this.goodDetail.goodsImage1),
					this.formatImageUrl(this.goodDetail.goodsImage2),
					this.formatImageUrl(this.goodDetail.goodsImage3)
				].filter(url => url);
			},

			formatImageUrl(path) {
				return path ? `http://localhost:8080${path}` : '';
			},

			async getUserProfile() {
				try {
					const res = await uni.request({
						url: 'http://localhost:8080/system/user/profile',
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});
					return res.data.code === 200 ? res.data.data.userId : null;
				} catch {
					return null;
				}
			},

			async checkCartStatus() {
				try {
					const res = await uni.request({
						url: 'http://localhost:8080/goodscart/goodscart/list',
						data: {
							goodsId: this.goodDetail.goodsId,
							userId: this.userId
						},
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});

					if (res.data.code === 200) {
						this.isInCart = res.data.rows.length > 0;
						if (this.isInCart) {
							this.cartItem = res.data.rows[0];
						}
					}
				} catch (error) {
					console.error('检查购物车状态失败:', error);
				}
			},

			async handleCartAction() {
				if (this.cartLoading) return;
				this.cartLoading = true;

				try {
					if (!this.userId) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return setTimeout(() => uni.navigateTo({
							url: '/pages/login/login'
						}), 1500);
					}

					if (this.isInCart) {
						await this.removeFromCart();
					} else {
						await this.addToCart();
					}
				} finally {
					this.cartLoading = false;
				}
			},

			async addToCart() {
				try {
					const res = await uni.request({
						url: 'http://localhost:8080/goodscart/goodscart',
						method: 'POST',
						header: {
							'Content-Type': 'application/json',
							'Authorization': uni.getStorageSync('token')
						},
						data: {
							userId: this.userId,
							goodsId: this.goodDetail.goodsId,
							addgoodsQuantity: 1
						}
					});

					if (res.data.code === 200) {
						this.isInCart = true;
						this.updateCartBadge(1);
						uni.showToast({
							title: '已加入购物车',
							icon: 'success'
						});
						await this.checkCartStatus(); // 刷新购物车数据
					}
				} catch (error) {
					this.handleCartError(error);
				}
			},

			async removeFromCart() {
				try {
					if (!this.cartItem) {
						await this.checkCartStatus();
						if (!this.cartItem) return;
					}

					const res = await uni.request({
						url: `http://localhost:8080/goodscart/goodscart/${this.cartItem.cartId}`,
						method: 'DELETE',
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});

					if (res.data.code === 200) {
						this.isInCart = false;
						this.updateCartBadge(-1);
						uni.showToast({
							title: '已移出购物车',
							icon: 'success'
						});
						this.cartItem = null;
					}
				} catch (error) {
					this.handleCartError(error);
				}
			},

			updateCartBadge(delta) {
				const current = parseInt(uni.getTabBarBadge({
					index: 2
				}) || 0);
				const newCount = Math.max(current + delta, 0);
				newCount > 0 ?
					uni.setTabBarBadge({
						index: 2,
						text: newCount.toString()
					}) :
					uni.removeTabBarBadge({
						index: 2
					});
			},

			handleCartError(error) {
				const msg = error.data?.msg || error.errMsg || '操作成功';
				uni.showToast({
					title: msg,
					icon: 'none'
				});
			},

			goBack() {
				uni.navigateBack();
			},
			handleShare() {
				uni.showToast({
					title: '分享成功',
					icon: 'none'
				});
			},
			handleCollect() {
				this.isCollected = !this.isCollected;
				uni.showToast({
					title: this.isCollected ? '已收藏' : '已取消',
					icon: 'none'
				});
			},

			// 立即购买处理逻辑
			async handleBuyNow() {
				// 检查登录状态
				if (!this.userId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return setTimeout(() => uni.navigateTo({
						url: '/pages/login/login'
					}), 1500);
				}

				// 构造订单数据（单个商品）
				const orderData = [{
					goodsId: this.goodDetail.goodsId,
					quantity: 1, // 默认购买数量为1
					cartId: null, // 立即购买不需要购物车ID
					goodsPrice: this.goodDetail.goodsPrice
				}];

				// 跳转订单页面
				uni.navigateTo({
					url: `/pages/order-payment/order-payment?items=${encodeURIComponent(
			      JSON.stringify(orderData)
			    )}&userId=${this.userId}`
				});
			}
		}
	};
</script>

<style>
	/* 导航栏样式 */
	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		/* padding: 15px;
		background: #fff;
		border-bottom: 1px solid #f0f0f0; */
		padding: 10rpx 15rpx;
		background: #FFF8F0;
		border-bottom: 1px solid #f0f0f0;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.3);
	}

	.nav-title {
		/* 	font-size: 18px;
		font-weight: 500; */

		font-size: 36rpx;
		font-weight: bold;
	}

	.cart-icon {
		padding: 5px;
	}

	.container {
		padding-bottom: 100px;
		background: #FFF8F0;
		/* 为底部导航栏留出空间 */
	}

	/* 页面标题 */
	.page-title {
		font-size: 18px;
		font-weight: bold;
		text-align: center;
		padding: 15px;
		background: #ffffff;
		border-bottom: 1px solid #f0f0f0;
	}

	/* 商品轮播图 */
	.swiper {
		/* 		height: 300px; */
		height: 250px;
		margin-bottom: 10px;
	}

	.swiper-img {
		width: 100%;
		height: 100%;
	}

	/* 商品详细介绍 */
	.product-detail {
		/* 		padding: 15px;
		background: #ffffff; */
		/* 		padding: 10px;
		background: #FFF8F0; */

		margin-bottom: 10px;
		background: white;
	}

	.product-name {
		/* 	font-size: 20px;
		font-weight: bold;
		margin-bottom: 10px; */
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 6rpx;
		margin-left: 10px;
	}

	.product-description {
		/* 	font-size: 14px;
		color: #666; */
		font-size: 14px;
		color: #666;
		margin-bottom: 6rpx;
		margin-left: 10px;
	}

	/* 商品价格和库存 */
	.price-stock {
		/* 	display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		background: #ffffff;
		border-bottom: 1px solid #f0f0f0; */
		/* margin-bottom: 10px; */

		/* 		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #dcd7d7;
		padding-bottom: 10px; */

		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #dcd7d7;
		padding-bottom: 10px;
	}

	.price {
		/* 	font-size: 18px;
		color: #e44d26;
		font-weight: bold; */
		font-size: 18px;
		color: #e44d26;
		font-weight: bold;
		margin-left: 10px;
	}

	.stock {
		/* font-size: 14px;
		color: #666; */
		font-size: 14px;
		color: #666;
		margin-right: 10px;
	}

	/* 评价部分 */
	.review-section {
		/* 		padding: 15px;
		background: #ffffff; */

		background: white;
	}

	.review-header {
		/* display: flex;
		align-items: center;
		margin-bottom: 15px;
		background: #FFF8F0; */

		/* 		display: flex;
		align-items: center;
		margin-bottom: 5px;
		margin-left: 10px; */

		display: flex;
		align-items: center;
		padding: 10px 0;
		margin-bottom: 1ps solid;
	}

	.rating {
		display: flex;
		align-items: center;
	}

	.rating-text {
		font-size: 18px;
		color: #e44d26;
		margin-left: 10px;
		/* margin-right: 10px; */
	}

	.review-count {
		/* 		font-size: 14px;
		color: #666; */
		font-size: 14px;
		color: #666;
		flex: 1;
		text-align: right;
		margin-right: 10px;
	}

	/* 用户评价列表 */
	.review-item {
		margin-bottom: 15px;
		border-bottom: 1px solid #dcd7d7;
	}

	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 10px;

		margin-left: 10px;
	}

	.user-avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.user-nickname {
		font-size: 14px;
		color: #333;
	}

	.review-content {
		margin-bottom: 10px;

		margin-left: 10px;
	}

	.review-text {
		font-size: 14px;
		color: #333;
	}

	.review-images {
		display: flex;
		gap: 10px;
		margin-top: 10px;
	}

	.review-img {
		width: 80px;
		height: 80px;
		border-radius: 5px;
	}

	.review-time {
		font-size: 12px;
		color: #999;
		text-align: right;
		margin-right: 10px;

		margin-bottom: 10px;
	}

	/* 底部导航栏 */
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-around;
		align-items: center;
		background: #ffffff;
		padding: 5px 0;
		/* padding: 10px 0; */
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
	}

	.footer-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		/* margin-left: 15px; */
	}

	.footer-text {
		font-size: 12px;
		color: #666;
		margin-top: 5px;
	}

	.cart,
	.buy {
		/* flex: 1; */
		width: 30%;
		text-align: center;
	}

	.buy {
		background: #f1e054;
		color: #333;
		padding: 10px;
		border-radius: 5px;
	}

	/* 原有样式保持不变 */

	.cart-loading {
		opacity: 0.7;
		pointer-events: none;
	}

	.footer-item:active {
		opacity: 0.8;
		transform: scale(0.95);
		transition: all 0.2s;
	}

	.buy {
		background: linear-gradient(135deg, #ffd700, #ffb300);
		box-shadow: 0 2rpx 8rpx rgba(255, 179, 0, 0.3);
	}

	/* 新增响应式布局 */
	@media (max-width: 375px) {
		.footer-text {
			font-size: 10px;
		}

		.uni-icons {
			font-size: 20px;
		}
	}
</style>
